import {
    $http
} from '@escook/request-miniprogram'
import auth from './auth'

//baseUrl
$http.baseUrl = 'http://localhost:8080'

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
    wx.showLoading({
        title: '加载中...',
    })
    var token = wx.getStorageSync('vl_token')
    if (options.url.indexOf('/getCode') == -1) {
      options.header = {
        'Authorization': 'Bearer ' + token,
      }
    }
}
// 请求完成之后做一些事情
$http.afterRequest = function () {
    wx.hideLoading()
}
/**
 * 拦截器
 */
const interceptor = async (url) => {
    console.log("=======进入拦截器=========");
    if (url.indexOf('/validateToken') == -1 && url.indexOf('/getCode') == -1) {
        console.log("=======拦截请求=========");
        const res =await auth.auth()
        return res;
    }
    return true
}
/**
 * get请求
 * @param {*} url 
 * @param {*} data 
 */
const get = (url, data) => {
    if (interceptor(url)) {
        if(data){
            return $http.get(url, data)
        }else{
            return $http.get(url)
        }
    }
    return new Promise(function (resolve, reject) {
        reject()
    })
}
/**
 * post请求
 * @param {url}} url 
 * @param {*} data 
 */
const post = (url, data) => {
    if (interceptor(url)) {
        if(data){
            return $http.post(url, data)
        }else{
            return $http.post(url)
        }
    }
    return new Promise(function (resolve, reject) {
        reject()
    })
}
module.exports = {
    get,
    post,
    interceptor
}